<template>
  <div class="app-container">
    <div class="app-container-inner">
      <div v-if="userStore.utype == 2">
        <el-button type="primary" @click="download" style="margin-right: 5%"
          >标准CSV文件下载</el-button
        >
        <div style="margin-left: 85%">
          <el-upload
            v-model:file-list="fileListCode"
            class="upload-demo"
            action="https://su75ks.laf.run/QRCode"
            :auto-upload="true"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="handleSuccess"
            :limit="1"
          >
            <el-button type="primary">党费缴纳二维码上传</el-button>
          </el-upload>
        </div>
        <div style="max-width: 800px" class="content">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            label-width="180px"
            class="demo-ruleForm"
            :size="formSize"
            :rules="rules"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email" placeholder="输入中大邮箱" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="ruleForm.phone" />
            </el-form-item>
            <el-form-item label="学号" prop="num">
              <el-input v-model="ruleForm.num" />
            </el-form-item>
            <el-form-item label="入学年份" prop="year">
              <el-input v-model="ruleForm.year" />
            </el-form-item>
            <el-form-item label="身份" prop="status">
              <el-radio-group v-model="ruleForm.status">
                <el-radio :label="'1'">本科生</el-radio>
                <el-radio :label="'2'">研究生</el-radio>
                <el-radio :label="'3'">博士生</el-radio>
                <el-radio :label="'4'">教职工</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div class="button">
            <el-button type="primary" @click="createOne" style="margin-right: 5%">创建</el-button>
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              action="https://su75ks.laf.run/batch_create_account"
              :auto-upload="true"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-success="handleSuccess"
              :limit="1"
            >
              <el-button type="primary">批量导入</el-button>
              <template #tip>
                <div class="el-upload__tip"> 请上传标准文件（模版可下载） </div>
              </template>
            </el-upload>
          </div>
        </div>
      </div>
      <div v-else>
        <Error></Error>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, onUnmounted, onMounted } from 'vue'
  import { ElMessage, ElNotification, ElMessageBox, type FormInstance } from 'element-plus'
  import type { UploadProps, UploadUserFile } from 'element-plus'
  import { Cloud } from 'laf-client-sdk'
  import Error from '@/views/error/404.vue'
  import watermark from '@/utils/watermark.js'
  import { useUserStore } from '@/store/modules/user'
  const APPID = 'su75ks' // Laf 应用 appid
  const cloud = new Cloud({
    baseUrl: `https://${APPID}.laf.run`,
    getAccessToken: () => userStore.token,
  })
  const formSize = ref('default')
  const setWaterMark = () => {
    //添加水印
    watermark.set(userStore.info.branch_name, userStore.num)
    //移除水印,传 null 移除水印
    //watermark.close()
  }
  onUnmounted(async () => {
    watermark.close(null)
  })
  onMounted(async () => {
    setWaterMark()
  })

  const ruleFormRef = ref<FormInstance>()
  const userStore = useUserStore()
  const ruleForm = ref({
    name: '',
    num: '',
    phone: '',
    email: '',
    year: 2021,
    utype: 1,
    status: '',
    branch_id: userStore._id,
  })
  const rules = reactive({
    year: [{ required: true, message: '请输入入学年份', trigger: 'blur' }],
    email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    studentNumber: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  })
  const fileList = ref<UploadUserFile[]>([])
  const fileListCode = ref<UploadUserFile[]>([])
  //删除文件后
  const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
    ElMessage('删除成功')
  }
  //删除文件前
  const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(`确定要删除 ${uploadFile.name} ?`).then(
      () => true,
      () => false,
    )
  }
  const handleSuccess: UploadProps['onSuccess'] = (file, uploadFiles) => {
    ElMessage('上传成功')
  }
  const createOne = async () => {
    const res = await cloud.invoke('create_account', ruleForm.value)
    if (res.code == 201) {
      ElNotification({
        message: res.msg,
        type: 'success',
        duration: 3000,
      })
    }
  }
  const download = async () => {
    const fileUrl = await cloud.invoke('getStandExcel')
    console.log(fileUrl)
    const link = document.createElement('a')
    link.href = fileUrl
    link.download = '党员标准csv表格.csv' // 替换为你要保存的文件名
    link.target = '_blank'
    link.rel = 'noopener noreferrer'
    link.click()
  }
</script>

<style scoped lang="scss">
  .content {
    margin-left: 10%;
    margin-top: 10%;
  }
  .button {
    display: flex;
    margin: 5% 25%;
    margin-left: 30%;
  }
</style>
